﻿using AutoMapper;
using B.S.BasicData.Api.Read.Application.Command.Menu;
using B.S.BasicData.Api.Read.Application.Command.User;
using B.S.BasicData.Domian.Entities.Menu;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interface;
using MediatR;

namespace B.S.BasicData.Api.Read.Application.Handler.Menu
{
    public class UpdateMenuHandler : IRequestHandler<UpdateMenuCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<MenuModel> meunRepo;
        private readonly IMapper mapper;

        public UpdateMenuHandler(IBaseRepository<MenuModel>meunRepo,IMapper mapper)
        {
            this.meunRepo = meunRepo;
            this.mapper = mapper;
        }
        public Task<ApiResult<int>> Handle(UpdateMenuCommand request, CancellationToken cancellationToken)
        {
            var res = new ApiResult<int>();
            var account = meunRepo.GetAll().Where(x => x.MenuName == request.MenuName && x.Id != request.Id).FirstOrDefault();
            if (account != null)
            {
                res.Message = "菜单名称已存在";
                res.Code = ApiEnum.Error;
                return Task.FromResult(res);
            }
            var entity = mapper.Map(request, account);
            var r = meunRepo.Update(entity).Result;
            if (r > 0)
            {
                res.Message = "修改成功";
                res.Code = ApiEnum.Ok;
                res.Data = r;
            }
            else
            {
                res.Message = "修改失败";
                res.Code = ApiEnum.Error;
                res.Data = r;
            }
            return Task.FromResult(res);

        }
    }
}
